<template>
	<a-drawer
		title="发送站内信"
		:width="500"
		:visible="visible"
		:destroy-on-close="true"
		:body-style="{ paddingBottom: '80px' }"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="主题：" name="subject">
				<a-input v-model:value.trim="formData.subject" placeholder="请输入主题" allow-clear/>
			</a-form-item>
			<a-form-item label="站内信分类：" name="category">
				<a-select
					v-model:value="formData.category"
					:options="categoryOptions"
					style="width: 100%"
					placeholder="请选择站内信分类"
				>
				</a-select>
			</a-form-item>
			<a-form-item label="正文：" name="content">
				<a-textarea v-model:value="formData.content" placeholder="请输入正文"
							:auto-size="{ minRows: 5, maxRows: 5 }"/>
			</a-form-item>
			<a-form-item label="接收人：" name="receiverIdList">
				<a-button type="primary" @click="openUserSelector">选择用户</a-button>
				<br/>
				<a-tag class="mt-3" v-for="(user, index) in userList" :key="user.id" color="cyan" closable
					   @close="removeUserTag(index)">
					{{ user.name }}
				</a-tag>
			</a-form-item>
		</a-form>

		<a-upload name="file" :show-upload-list="false" :custom-request="uploadFile">
			<a-button type="primary">
				<UploadOutlined/>
				上传附件
			</a-button>
		</a-upload>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:showPagination="false"
			bordered
			:row-key="(record) => record.id"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-popconfirm title="确定要删除吗？" @confirm="deleteFile(record)">
						<a-button type="link" danger size="small">删除</a-button>
					</a-popconfirm>
				</template>
			</template>
		</s-table>

		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button style="margin-right: 8px" type="info" @click="onSubmit(1)" :loading="sendLoading">草稿</a-button>
			<a-button type="primary" @click="onSubmit(2)" :loading="sendLoading">发送</a-button>
		</template>
	</a-drawer>
	<user-selector-plus
		ref="UserSelectorPlus"
		page-url="/sys/org/userSelector"
		org-url="/sys/org/orgTreeSelector"
		@onBack="userBack"
	/>
</template>

<script setup name="messageForm">
	import {required} from '@/utils/formRules'
	import {message} from 'ant-design-vue'
	import messageApi from '@/api/dev/messageApi'
	import fileApi from '@/api/dev/fileApi'
	import userSelectorPlus from '@/components/Selector/userSelectorPlus.vue'

	const sendLoading = ref(false)
	let UserSelectorPlus = ref()
	// 定义emit事件
	const emit = defineEmits({successful: null})
	const {proxy} = getCurrentInstance()
	// 默认是关闭状态
	let visible = $ref(false)
	const formRef = ref()

	const tableData = ref([])

	const uploadFileIds = ref([])
	const columns = [
		{
			title: '文件名',
			dataIndex: 'name',
			ellipsis: true
		},
		{
			title: '大小',
			dataIndex: 'sizeInfo',
			ellipsis: true
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center'
		}
	]
	// 表格查询 返回 Promise 对象
	const loadData = (parameter) => {
		if(uploadFileIds.value.length === 0) return new Promise((resolve)=> resolve([]))
		return fileApi.fileList(Object.assign(parameter, {
			fileIds:uploadFileIds.value.join(',')
		})).then((data) => {
			// console.log('data=', data)
			tableData.value = data
			return data
		})
	}

	// 表单数据
	const formData = ref({})
	// 定义tableDOM
	const table = ref(null)
	const userList = ref([])
	// 打开抽屉
	const onOpen = (record) => {
		visible = true
		if (record) loadDetail(record)
	}
	// 关闭抽屉
	const onClose = () => {
		visible = false
		userList.value = []
		tableData.value = []
		uploadFileIds.value = []
	}
	// 默认要校验的
	const formRules = {
		subject: [required('请输入主题')],
		category: [required('请选择站内信分类')]
	}
	// 站内信分类字典
	let categoryOptions = proxy.$TOOL.dictTypeList('MESSAGE_CATEGORY').map((item) => {
		return {
			value: item['dictValue'],
			label: item['name']
		}
	})
	// 打开人员选择器
	const openUserSelector = () => {
		let ids = []
		// 打开之前选判断我们刚刚是否选过
		if (userList.value.length > 0) {
			userList.value.forEach((item) => {
				ids.push(item.id)
			})
		}
		UserSelectorPlus.value.showUserPlusModal(ids)
	}
	// 人员选择回调
	const userBack = (value) => {
		userList.value = value
	}
	// 删除某用户
	const removeUserTag = (idx) => {
		// console.log('index=',index)
		userList.value = userList.value.filter((item, index) => index !== idx)
		// console.log(userList.value)
	}
	// 验证并提交数据
	// '0-关闭 1-草稿 2-发布(默认1-草稿)';
	const onSubmit = (state) => {
		formRef.value.validate().then(() => {
			if (userList.value.length < 1) {
				message.warning('未选择接收消息人员')
				return
			}
			convFormData()
			addAttachmentFile()
			sendLoading.value = true
			messageApi
				.messageSend({
					...formData.value,
					state
				})
				.then(() => {
					emit('successful')
					onClose()
				})
				.finally(() => {
					sendLoading.value = false
				})
		})
	}
	// 添加接收人
	const convFormData = () => {
		let ids = []
		userList.value.forEach((item) => {
			ids.push(item.id)
		})
		formData.value.receiverIdList = ids
	}
	// 添加附件
	const addAttachmentFile = () => {
		formData.value.fileIds = tableData.value.map(item => item.id)
	}
	// 上传本地文件
	const uploadFile = (data) => {
		// uploadLoading.value = true
		const fileData = new FormData()
		fileData.append('file', data.file)
		fileApi.fileUploadDynamicReturnId(fileData)
			.then((fileId) => {
				message.success('上传成功')
				uploadFileIds.value.push(fileId)
				table.value.refresh(true)
			})
			.finally(() => {
				// uploadLoading.value = false
			})
	}
	const deleteFile = (data) => {
		uploadFileIds.value = uploadFileIds.value.filter(id => id !== data.id)
		fileApi.fileDelete([data])
		table.value.refresh(true)
	}

	const loadDetail = (record) => {
		const param = {
			id: record.id
		}
		messageApi.messageDetail(param).then((data) => {
			Object.assign(record, data)
			formData.value = record
			// console.log('data.receiveInfoList=', data.receiveInfoList)
			userList.value = data.receiveInfoList.map(item => {
				return {
					id: item.receiveUserId,
					name: item.receiveUserName
				}
			})
			uploadFileIds.value = data.fileIds
			table.value.refresh(true)
			convFormData()
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
